<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @refresh-change="refreshChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="primary"
                   size="small"
                   icon="el-icon-plus"
                   plain
                   v-if="permissionList['addBtn']"
                   @click="handleAdd">新 增
        </el-button>
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permissionList['delBtn']"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template slot="menu" slot-scope="scope">
        <el-button type="text"
                   size="small"
                   icon="el-icon-view"
                   v-if="permissionList['viewBtn']"
                   @click="handleDetail(scope.row)">详 情
        </el-button>
        <el-button type="text" size="small">
          <el-dropdown type="primary" size="small">
            <span class="el-dropdown-link">
              更 多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu type="primary" slot="dropdown">
              <el-dropdown-item
                v-if="permissionList['assignBtn']"
                @click.native="handleAssign(scope.row)">课程分配
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-button>
      </template>
    </avue-crud>

    <el-dialog title="详 情" :visible.sync="dialogDetailVisible">
      <avue-form :option="detailFormOption" v-model="detailData"></avue-form>
      <h2>已选课程</h2>
      <avue-crud :option="detailTableOption" v-model="detailTableData"></avue-crud>
    </el-dialog>

    <!--  分配课程选择表  -->
    <el-dialog title="课程分配" :visible.sync="dialogCourseTableVisible">
      <el-divider content-position="left">已选课程</el-divider>
      <avue-crud :option="courseOption"
                 :table-loading="dialogOwnCourseLoading"
                 :data="ownCourseData"
                 :page="ownCoursePage"
                 :permission="permissionList"
                 ref="crud-dialog"
                 @on-load="onDialogOwnLoad">
        <template slot-scope="scope" slot="menu">
          <el-button type="text"
                     size="small"
                     icon="el-icon-close"
                     v-if="permissionList['assignBtn']"
                     @refresh-change="refreshOwnChange"
                     @click="handleExclude(scope.row)">移 除
          </el-button>
        </template>
      </avue-crud>
      <el-divider content-position="left">可选课程</el-divider>
      <avue-crud :option="courseOption"
                 :table-loading="dialogOptionalCourseLoading"
                 :data="optionalCourseData"
                 :page="optionalCoursePage"
                 :permission="permissionList"
                 ref="crud-dialog"
                 @on-load="onDialogOptionalLoad">
        <template slot-scope="scope" slot="menu">
          <el-button type="text"
                     size="small"
                     icon="el-icon-check"
                     v-if="permissionList['assignBtn']"
                     @refresh-change="refreshOptionalChange"
                     @click="handleChoose(scope.row)">选 择
          </el-button>
        </template>
      </avue-crud>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, assignCourse, excludeCourse} from "@/api/basic/student";
  import {getOwnCourseList, getOptionalCourseList} from "@/api/basic/course";
  import {tableOption, detailFormOption, detailTableOption} from "@/const/crud/basic/student";
  import {courseOption} from "@/const/crud/basic/course";
  import {mapGetters} from "vuex";

  export default {
    data() {
      return {
        form: {},
        query: {},
        courseQuery: {
          studentId: ''
        },
        queryCourse: {},
        loading: false,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        ownCoursePage: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        optionalCoursePage: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: tableOption,
        detailFormOption: detailFormOption,
        detailTableOption: detailTableOption,
        data: [],
        detailData: [],
        detailTableData: [],
        ownCourseData: [],
        optionalCourseData: [],
        dialogDetailVisible: false,
        dialogCourseTableVisible: false,
        dialogOwnCourseLoading: false,
        dialogOptionalCourseLoading: false,
        courseOption: courseOption,
        selectCourseData: [],
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.student_add, false),
          viewBtn: this.vaildData(this.permission.student_view, false),
          delBtn: this.vaildData(this.permission.student_delete, false),
          editBtn: this.vaildData(this.permission.student_edit, false),
          assignBtn: this.vaildData(this.permission.student_assign, true)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      rowSave(row, done, loading) {
        add(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleAdd() {
        this.$refs.crud.rowAdd();
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          return remove(this.ids);
        }).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
      },
      handleDetail(row) {
        this.detailData = row;
        this.dialogDetailVisible = true;
      },
      handleAssign(row) {
        this.courseQuery.studentId = row.id;
        this.dialogCourseTableVisible = true;
      },
      handleExclude(row) {
        this.$confirm("确定移除 " + row.name + " 课程吗?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.dialogOwnCourseLoading = true;
          return excludeCourse(row.id);
        }).then(res => {
          this.$message({
            type: "success",
            message: res.data.msg
          });
          this.ownCoursePage.currentPage = 1;
          this.optionalCoursePage.currentPage = 1;
          this.onDialogOwnLoad(this.ownCoursePage);
          this.onDialogOptionalLoad(this.optionalCoursePage);
        }).finally(() => {
          this.dialogOwnCourseLoading = false;
        });
      },
      refreshOwnChange() {
        this.onDialogOwnLoad(this.ownCoursePage, this.queryCourse);
      },
      handleChoose(row) {
        let _this = this;
        this.$confirm("确定分配 " + row.name + " 课程吗?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.dialogOptionalCourseLoading = true;
          return assignCourse(Object.assign({
            studentId: _this.courseQuery.studentId,
            courseId: row.id
          }));
        }).then(res => {
          this.$message({
            type: "success",
            message: res.data.msg
          });
          this.ownCoursePage.currentPage = 1;
          this.optionalCoursePage.currentPage = 1;
          this.onDialogOwnLoad(this.ownCoursePage);
          this.onDialogOptionalLoad(this.optionalCoursePage);
        }).finally(() => {
          this.dialogOptionalCourseLoading = false;
        })
      },
      refreshOptionalChange() {
        this.onDialogOptionalLoad(this.optionalCoursePage, this.queryCourse);
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      refreshChange(params) {
        this.onLoad(this.page, params);
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(
          page.currentPage,
          page.pageSize,
          Object.assign(params, this.query)
        ).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
      onDialogOwnLoad(page, params = {}) {
        this.dialogOwnCourseLoading = true;
        getOwnCourseList(
          page.currentPage,
          page.pageSize,
          Object.assign(params, this.courseQuery)
        ).then(res => {
          const data = res.data.data;
          this.ownCoursePage.total = data.total;
          this.ownCourseData = data.records;
          this.dialogOwnCourseLoading = false;
        })
      },
      onDialogOptionalLoad(page, params = {}) {
        this.dialogOptionalCourseLoading = true;
        getOptionalCourseList(
          page.currentPage,
          page.pageSize,
          Object.assign(params, this.courseQuery)
        ).then(res => {
          const data = res.data.data;
          this.optionalCoursePage.total = data.total;
          this.optionalCourseData = data.records;
          this.dialogOptionalCourseLoading = false;
        })
      }
    }
  };
</script>

<style lang="scss" scoped>
.el-select-dropdown {
  width: 100%;
  .el-scrollbar {
    .el-select-dropdown__wrap {
      margin: 0 !important;
    }
  }
}
.el-dropdown-link {
  cursor: pointer;
  font-size: 12px;
  color: #409EFF;
}
.el-icon-arrow-down {
  font-size: 12px;
}
</style>
